package com.njwb.day17.yinhang;

// 账户类
class Account {
    private double balance; // 余额

    public Account(double balance) {
        this.balance = balance;
    }

    // 存款方法（减少锁粒度）
    public void deposit(double amount, String user) {
        System.out.println(user + " 正在存款 " + amount + " 元...");
        synchronized (this) { // 仅在修改余额时加锁
            balance += amount;
            System.out.println(user + " 存款成功，当前余额: " + balance + " 元");
        }
    }

    // 取款方法（减少锁粒度）
    public void withdraw(double amount, String user) {
        System.out.println(user + " 正在取款 " + amount + " 元...");
        synchronized (this) { // 仅在判断和修改余额时加锁
            if (balance >= amount) {
                balance -= amount;
                System.out.println(user + " 取款成功，当前余额: " + balance + " 元");
            } else {
                System.out.println(user + " 取款失败，余额不足！");
            }
        }
    }

    public double getBalance() {
        return balance;
    }
}
